package com.example.customview

import android.os.Bundle
import androidx.fragment.app.Fragment
import com.alibaba.android.arouter.facade.annotation.Autowired
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.android.arouter.launcher.ARouter
import com.android.baselibrary.arouter.ArouterContains
import com.android.baselibrary.base.BaseActivity
import com.example.customview.arouter.CustomArouter
import com.example.customview.databinding.ActivityCustomBinding

/**
 * 自定义容器类
 */
@Route(path =CustomArouter.CUSTOM_CONTAINER_ACTIVITY)
class CustomActivity:BaseActivity<ActivityCustomBinding>() {

    @JvmField
    @Autowired(name = CustomArouter.EXTRA_KEY_FRAGMENT_PATH)
    var fragmentPath:String? = null

    override fun getLayoutId(): Int = R.layout.activity_custom

    override fun initView() {
        initFragments()
    }

    private fun initFragments() {
        if (fragmentPath.isNullOrEmpty()) {
            finish()
            return
        }
        var fragment = supportFragmentManager.findFragmentByTag(fragmentPath)
        if (fragment == null) {
            fragment = ARouter.getInstance().build(fragmentPath).navigation() as Fragment?
            if (fragment == null) {
                finish()
                return
            }
           copyExtras2Fragment(fragment)
        }
        supportFragmentManager.beginTransaction().replace(R.id.fl_container, fragment,fragmentPath)
            .commitAllowingStateLoss()
    }
    private fun copyExtras2Fragment(fragment: Fragment) {
        var arguments = fragment.arguments
        if (arguments == null) {
            arguments = Bundle()
            fragment.arguments = arguments
        }
        val extras = intent.extras
        extras?.run {
            arguments.putAll(extras)
        }
    }

    override fun initListener() {

    }
}